/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.digwener.entities.connectors;

import com.digwener.entities.EntityHolder;
import com.digwener.entities.EntityException;
import java.io.File;
import java.util.List;
import javax.xml.bind.*;

/**
 *
 * @author Anton
 */
public  class ConnectorHolder implements EntityHolder {
    
    private static ConnectorHolder instance = null;
    private ConnectorHolder(){}
    
    public static ConnectorHolder getInstance(){
        if(instance == null){
            instance = new ConnectorHolder();
        }
        
        return instance;
    }
    
    private List<ConnectorType> connectorsList;
    
    public List<ConnectorType> getConnectorsList(){
        return connectorsList;
    }
    
    public void loadFromXML(){
        JAXBElement<ConnectorListType> jaxbConnections = null;
        try{
           JAXBContext jc = JAXBContext.newInstance("com.digwener.entities.connectors"); 
           Unmarshaller m = jc.createUnmarshaller();	
           File f = new File("db.xml");
           jaxbConnections =(JAXBElement<ConnectorListType>) m.unmarshal(f); 
        }catch(JAXBException je)
		{
			String message = je.getMessage();
			System.out.println(message);
		}
        
        ConnectorListType connectorsElem = jaxbConnections.getValue();
        connectorsList = connectorsElem.getConnectors();      
    }
    
    @Override
    public void saveToXML(){
        ObjectFactory factory = new ObjectFactory();
        ConnectorListType connectorsElem = factory.createConnectorListType();
        connectorsElem.setConnectors(connectorsList);
        JAXBElement<ConnectorListType> jaxbConnections = factory.CreateConnectors(connectorsElem);
        try{
            JAXBContext jc = JAXBContext.newInstance("com.digwener.entities.connectors"); 
            Marshaller m = jc.createMarshaller();	
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            File f = new File("db_debug.xml");
            m.marshal(jaxbConnections, f);
        }catch(JAXBException je)
        {
                String message = je.getMessage();
                System.out.println(message);
        }
    }
    
    ConnectorType getConnectorByName(String name) throws EntityException{
        if (connectorsList == null)
            throw new EntityException("Connection Holder is not initialized");
        
        ConnectorType result = null;
        
        for(ConnectorType connector:connectorsList){
            if(connector.getInstanceName().equals(name))
                return connector;
        }
        
        throw new EntityException("Specified connector does not exist");
    }
}
